package com.ypj.indusynergyems.web;

import com.ypj.indusynergyems.dao.entity.CartEntity;
import com.ypj.indusynergyems.dao.entity.UserEntity;
import com.ypj.indusynergyems.service.IOrderService;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@Controller
@RequiredArgsConstructor
public class OrderController {

    private final IOrderService orderService;

    @PostMapping("/addToCar")
    public @ResponseBody String addToCar(int goodsId, int num, int price, int shopId,HttpSession session){
        int user_id = ((UserEntity)session.getAttribute("user")).getUserId();
        return orderService.addCart(goodsId,num,price,user_id,shopId);
    }


    //查询我的购物车
    @GetMapping("/cart/myCart")
    public String findMyCartList(HttpSession session , Model model){
        //获取session中的用户id
        int user_id = ((UserEntity)session.getAttribute("user")).getUserId();
        //调service中的方法
        List<CartEntity> carts =  orderService.findMyCartList(user_id);
        model.addAttribute("carts",carts);

//        //查询我的用户下的所有收货地址
//        List<RecipientEntity>  recipients = homeFoodService.findAllRecipient(user_id);
//        model.addAttribute("recipients",recipients);
        return "goodsCar/cartList";
    }

    // /toTrade 去结算
    @PostMapping("/toTrade")
    public @ResponseBody String toTrade(@RequestParam("selectedValues") String selectedValues,Model model,HttpSession session){
        System.out.printf("selectedValues：======"+selectedValues);
        //解析获取到的字符串去除逗号并在数据库中差选所选商品
        String[] split = selectedValues.split(",");
        //将字符串数组转译为int数组
        int[] ints = Arrays.stream(split).mapToInt(Integer::parseInt).toArray();
        for(int i = 0;i<ints.length;i++){
            System.out.println(ints[i]);
        }
        List<CartEntity> carts = orderService.findMySelectGoodsList(ints);
        System.out.println("carts"+ carts.size());
        session.setAttribute("carts",carts);
        return "success";
    }

    @GetMapping("/total/total")
    public String toPay(){
        return "total/total";
    }



}
